package pkg

import (
	"fmt"
	"github.com/golang-jwt/jwt/v4"
	"time"
)

const JWTSecretKey = "shenzhou"
const JWTSeconds = 86400

// @secretKey: JWT 加解密密钥
// @iat: 时间戳
// @seconds: 过期时间，单位秒
// @payload: 数据载体
func GetJwtToken(userid int64) (string, error) {
	iat := time.Now().Unix()
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + JWTSeconds
	claims["iat"] = iat
	claims["userid"] = userid
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(JWTSecretKey))
}
func ParseJwtToken(tokenString string) (userid int64, err error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { return []byte(JWTSecretKey), nil })

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return int64(claims["userid"].(float64)), nil
	} else {
		return 0, fmt.Errorf("token invaild")
	}
}
